<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :rules="ruleQuery" :inline="true" v-show="showSearch" label-width="68px">
      <el-autocomplete
        popper-class="my-autocomplete"
        v-model="queryParams.term"
        prop="term"
        clearable
        :fetch-suggestions="querySearch"
        placeholder="es搜索带补全"
        @select="handleSelect">
        <i
          class="el-icon-edit el-input__icon"
          slot="suffix"
          @click="handleIconClick">
        </i>
        <template slot-scope="{ item }">
          <div class="name">{{ item.title }}</div>
          <span class="addr">{{ item.content }}</span>
        </template>
      </el-autocomplete>

      <!--<el-form-item label="es搜索" prop="term">-->
      <!--  <el-input-->
      <!--    v-model="queryParams.term"-->
      <!--    placeholder="es搜索带补全"-->
      <!--    clearable-->
      <!--    @input="onInput"-->
      <!--    @keyup.enter.native="handleQuery"-->
      <!--  />-->
      <!--  <ul>-->
      <!--    <li v-for="suggestion in suggestList" :key="suggestion.id">-->
      <!--      {{ suggestion }}-->
      <!--    </li>-->
      <!--  </ul>-->
      <!--</el-form-item>-->
      <el-form-item style="margin-left: 10px">
        <el-radio-group v-model="queryParams.sortOrder" size="small">
          <el-radio-button label="DESC">价格降序</el-radio-button>
          <el-radio-button label="ASC">价格升序</el-radio-button>
        </el-radio-group>

      </el-form-item>

      <el-form-item label="价格范围" prop="numBegin">
        <el-row>
          <el-col :span="10">
            <el-input
              v-model="queryParams.numBegin"
              style="width: 70px; margin-right: 10px"
            />
          </el-col>
          <el-col :span="4" style="text-align: center; line-height: 32px;">
            ~
          </el-col>
          <el-col :span="10">
            <el-input
              v-model="queryParams.numEnd"
              ref="numEnd"
              prop="numEnd"
              style="width: 70px; margin-left: 10px"
            />
          </el-col>
        </el-row>
      </el-form-item>


      <el-form-item style="margin-left: 12px">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">es分页搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAddAll"
        >数据全量同步es
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:article:add']"
        >新增同步es
        </el-button>
      </el-col>
      <!--<el-col :span="1.5">-->
      <!--  <el-button-->
      <!--    type="success"-->
      <!--    plain-->
      <!--    icon="el-icon-edit"-->
      <!--    size="mini"-->
      <!--    :disabled="single"-->
      <!--    @click="handleUpdate"-->
      <!--    v-hasPermi="['system:article:edit']"-->
      <!--  >修改-->
      <!--  </el-button>-->
      <!--</el-col>-->
      <!--<el-col :span="1.5">-->
      <!--  <el-button-->
      <!--    type="danger"-->
      <!--    plain-->
      <!--    icon="el-icon-delete"-->
      <!--    size="mini"-->
      <!--    :disabled="multiple"-->
      <!--    @click="handleDelete"-->
      <!--    v-hasPermi="['system:article:remove']"-->
      <!--  >删除-->
      <!--  </el-button>-->
      <!--</el-col>-->
      <!--<el-col :span="1.5">-->
      <!--  <el-button-->
      <!--    type="warning"-->
      <!--    plain-->
      <!--    icon="el-icon-download"-->
      <!--    size="mini"-->
      <!--    @click="handleExport"-->
      <!--    v-hasPermi="['system:article:export']"-->
      <!--  >导出-->
      <!--  </el-button>-->
      <!--</el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
      <!--<el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="主键id" align="center" prop="id"/>
      <el-table-column label="标题" align="center">
        <template slot-scope="scope">
          <span v-html="scope.row.title"></span>
        </template>
      </el-table-column>
      <el-table-column label="内容" align="center">
        <template slot-scope="scope">
          <span v-html="scope.row.content"></span>
        </template>
      </el-table-column>
      <el-table-column label="金额" align="center" prop="price"/>
      <el-table-column label="补全建议数组字段" align="center" prop="suggestionText"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文章表的增删改查对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="内容">
          <el-input type="textarea" v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="金额" prop="price">
          <el-input v-model="form.price" placeholder="请输入金额"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addArticleAll,
  listArticle,
  getArticle,
  delArticle,
  addArticle,
  updateArticle,
  getArticleSuggestionText,
} from "@/api/article/articleSearch";

// 定义金额校验函数

export default {
  name: "ArticleSearch",
  data() {
    const isComplexMoney = (value) => {
      const reg = /^\d+(\.\d{1,2})?$/; // 正则表达式，匹配正数，最多两位小数
      return reg.test(value);
    };

    const validateCom = (rule, value, callback) => {
      const numEndNum = this.queryParams.numEnd;
      console.log('numEndNum', numEndNum)
      if (!isComplexMoney(value) || !isComplexMoney(numEndNum)) {
        callback(new Error('请输入正确格式的金额'));
      } else if (parseFloat(value) >= parseFloat(numEndNum)) {
        callback(new Error(`最大值输入值必须大于${value}`));
      } else if (value.length > 7 || numEndNum.length > 7) {
        callback(new Error('输入值不能超过6位')); //包含小数点位数
      } else if (value.length > 6) {
        callback(new Error('输入最小值不能超过6位'));
      } else if (numEndNum.length > 6) {
        callback(new Error('输入最大值不能超过6位'));
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文章表的增删改查表格数据
      articleList: [],
      restaurants: [],
      state: '',
      timeout:  null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        id: null,
        pageNum: 1,
        pageSize: 10,
        term: null,
        sortOrder: "DESC",
        sortField: "price",
        title: null,
        content: null,
        price: null,
        numBegin: null,
        numEnd: null
      },
      // 表单参数
      form: {},

      // 表单校验
      rules: {

      },
      // 表单校验
      ruleQuery: {
        numBegin: [{validator: validateCom, trigger: 'blur'}],
      }
    };
  },
  created() {
    this.getList();
    this.loading = false;
  },
  mounted() {
    // this.loadAll();
  },
  methods: {

    querySearch(queryString, cb) {
      getArticleSuggestionText(this.queryParams).then(response => {
        this.restaurants = [];
        this.restaurants = response.data;
        for (var i = 0; i < this.restaurants.length; i++) {
          this.restaurants[i].value = this.restaurants[i].title
        }
        var restaurants =this.restaurants;
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        cb(results);

      });
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1);
      };
    },


    handleSelect(item) {
      console.log(item);
      this.queryParams.term = item.title
      this.getList()
    },
    handleIconClick(ev) {
      console.log(ev);
    },

    /** 查询文章表的增删改查列表 */
    getList() {
      this.loading = true;
      listArticle(this.queryParams).then(response => {
        console.log(response)
        this.articleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        content: null,
        price: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文章表的增删改查";
    },
    /** 新增按钮操作 */
    handleAddAll() {
      addArticleAll(this.form).then(response => {
        this.$modal.msgSuccess("同步成功！");
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getArticle(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文章表的增删改查";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateArticle(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addArticle(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除文章表的增删改查编号为"' + ids + '"的数据项？').then(function () {
        return delArticle(row);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/article/export', {
        ...this.queryParams
      }, `article_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
em {
  //background-color: red;
  font-style: normal;
  color: red;
  font-weight: bold;
}
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
</style>
